import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { MainLayout } from "../../components";
import React, { useState, useEffect } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { Row, Col, Input, Upload, Select, Button } from "antd";
import { useAppSelector } from "../../app/hooks";
import { UploadRequestOption } from "rc-upload/lib/interface";
import axios from "axios";
import { useNavigate } from "react-router-dom";
function MyEditor() {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法
  const naviagte = useNavigate();
  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: "请输入内容...",
    // 菜单配置
    MENU_CONF: {
      uploadImage: {
        server: "/api/upload",
        fieldName: "chunk",
      },
    },
  };

  // 数据
  const [data, setData] = useState({
    src: "",
    title: "",
    content: "",
    avator: useAppSelector((state) => state.user.avator),
    auther: useAppSelector((state) => state.user.nickname),
    type: "去中心化应用",
    html: "",
  });

  const publish = async () => {
    const resp = await axios.post("/api/list", data);
    const { code } = resp.data;
    if (code === 200) {
      naviagte("/home");
    }
  };

  const customRequest = async (options: UploadRequestOption) => {
    const file = options.file as File;
    const formData = new FormData();
    formData.append("chunk", file, file.name);
    const resp = await axios.post("/api/upload", formData);
    setData({
      ...data,
      src: resp.data.data.url,
    });
    return Upload.LIST_IGNORE;
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <MainLayout>
      <div style={{ padding: 20 }}>
        <Row style={{ margin: "10px 0" }}>
          <Col span={2}>
            <span>标题：</span>
          </Col>
          <Col span={18}>
            <Input
              value={data.title}
              onChange={(e) => setData({ ...data, title: e.target.value })}
            ></Input>
          </Col>
        </Row>
        <Row style={{ margin: "10px 0" }}>
          <Col span={2}>
            <span>描述：</span>
          </Col>
          <Col span={18}>
            <Input
              value={data.content}
              onChange={(e) => setData({ ...data, content: e.target.value })}
            ></Input>
          </Col>
        </Row>
        <Row style={{ margin: "10px 0" }}>
          <Col span={2}>
            <span>上传</span>
          </Col>
          <Col span={18}>
            <Upload customRequest={customRequest}>
              <Button type="primary">选择图片</Button>
            </Upload>
            {data.src && (
              <img
                src={data.src}
                alt=""
                width={300}
                height={300}
                style={{ objectFit: "cover" }}
              />
            )}
          </Col>
        </Row>
        <Row style={{ margin: "10px 0" }}>
          <Col span={2}>
            <span>分类：</span>
          </Col>
          <Col span={18}>
            <Select
              value={data.type}
              onChange={(value) => setData({ ...data, type: value })}
              options={[
                {
                  label: "去中心化应用",
                  value: "去中心化应用",
                },
                {
                  label: "公链",
                  value: "公链",
                },
                {
                  label: "联盟链",
                  value: "联盟链",
                },
                {
                  label: "layer2",
                  value: "layer2",
                },
                {
                  label: "编程语言",
                  value: "编程语言",
                },
              ]}
            ></Select>
          </Col>
        </Row>
        <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: "1px solid #ccc" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={data.html}
            onCreated={setEditor}
            onChange={(editor) =>
              setData((state) => ({ ...state, html: editor.getHtml() }))
            }
            mode="default"
            style={{ height: "500px", overflowY: "hidden" }}
          />
        </div>
        <Button type="primary" block onClick={() => publish()}>
          发标题
        </Button>
      </div>
    </MainLayout>
  );
}

export default MyEditor;
